<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Modern UI CSS">
    <meta name="author" content="Sergey Pimenov">
    <meta name="keywords" content="windows 8, modern style, modern ui, style, modern, css, framework">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	    
    <link href="css/modern.css" rel="stylesheet">
    <link href="css/site.css" rel="stylesheet" type="text/css">
    <link href="js/google-code-prettify/prettify.css" rel="stylesheet" type="text/css">

    <script src="js/jquery-1.8.2.min.js"></script>
    <script src="js/google-analytics.js"></script>
    <script src="js/github.info.js"></script>
    <script src="js/google-code-prettify/prettify.js"></script>
    <script src="js/pagecontrol.js"></script>
    <script src="js/carousel.js"></script>
    
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuRlWO5oRKoOHe121hi1i5y0etUQmGkZg&sensor=false">
    </script>
    <script type="text/javascript">
    var map;
    var flightSymbol;
    var geocoder;
    var departureTimeArray;
    var departureAddressArray;
    var arrivalAddressArray;
    var flightIDArray;
    var speed = 800;
    var distance;
    var location1;
    var location2;
    var image;
     
    function initialize() {
    	geocoder = new google.maps.Geocoder();
    	image = new Image();
    	
    	//dummy data
    	departureTimeArray = new Array();
    	departureAddressArray = new Array();
    	arrivalAddressArray = new Array();
    	flightIDArray = new Array();
    	
    	/*addressArray[0] = {start:"vancouver ubc",stop:"vancouver metrotown"};
    	addressArray[1] = {start:"Hong Kong",stop:"vancouver"};
    	addressArray[2] = {start:"Mongolia",stop:"Iran"};
    	
    	timeArray[0] = {departYear:"2012",departMonth:"11",departDay:"25",departHour:"15",departMinute:"02",departSecond:"30"};
    	timeArray[1] = {departYear:"2012",departMonth:"11",departDay:"25",departHour:"10",departMinute:"20",departSecond:"30"};
    	timeArray[2] = {departYear:"2012",departMonth:"11",departDay:"26",departHour:"9",departMinute:"20",departSecond:"30"};*/
		
    	//real data
		departureTimeArray = ${departureTime};
    	departureAddressArray = ${departureLocation};
		arrivalAddressArray = ${arrivalLocation};
		flightIDArray = ${flightID};
		
		//console.log(arrivalAddressArray[0]);
		
    	//create map
      	var mapOptions = {
          center: new google.maps.LatLng(27.672003, -171.549518),
          zoom: 2,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
      	
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
        
        //create the flight plane symbol
        flightSymbol = {
                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                scale: 4,
                strokeColor: '#4AB84A',
              };
        
        //create polyline
        for (var i=0;i<departureAddressArray.length;i++)
        {
        	var polyline = new google.maps.Polyline({
            	strokeWeight: 3,
            	strokeColor: '#FFFFFF',
            	icons: [{
            	      icon: flightSymbol,
           		      offset: '100%',
           		    }],
           		map:map
          	});
        	
        	//draw and animate the polylines
    		drawPolyline(departureAddressArray[i],arrivalAddressArray[i],departureTimeArray[i],flightIDArray[i],polyline);
            //animateFlight(polyline);
        }
     }

    function drawPolyline (departureAddress,arrivalAddress,departureTime,flightID,polyline)
    {
    		var path = polyline.getPath();
    		var departureMarker;
    		var arrivalMarker;

    		geocoder.geocode( { 'address': departureAddress}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) 
                {
                  //map.setCenter(results[0].geometry.location);
                  var addressString = "Departure Address: " + departureAddress + "<br \>";
                  var flightIDString = "Flight ID: " + flightID;
                  var combinedString = addressString.concat(flightIDString);
                  
                  var infowindow = new google.maps.InfoWindow({
    					content: combinedString
				   });
                  departureMarker = new google.maps.Marker({
                      map: map,
                      position: results[0].geometry.location,
                      title:departureAddress,
                      animation: google.maps.Animation.DROP
                  });

                  path.push (results[0].geometry.location);
               	  
                  location1 = {lat:results[0].geometry.location.lat(),lng:results[0].geometry.location.lng()};
                  
                  google.maps.event.addListener(departureMarker, 'click', function() {
                	  infowindow.open(map,departureMarker);
                	});
                  }
                
                else 
                {
                  alert("Geocode was not successful for the following reason: " + status);
                }
              });
    		
    		geocoder.geocode( { 'address': arrivalAddress}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK)
                {
                  //map.setCenter(results[0].geometry.location);
                  var addressString = "Arrival Address: " + arrivalAddress + "<br \>";
                  var flightIDString = "Flight ID: " + flightID;
                  var combinedString = addressString.concat(flightIDString);
                  
                  var infowindow = new google.maps.InfoWindow({
    					content: combinedString
				   });
                  arrivalMarker = new google.maps.Marker({
                      map: map,  
                      position: results[0].geometry.location,
                      title:arrivalAddress,
                      animation: google.maps.Animation.DROP
                  });

                  path.push (results[0].geometry.location);
               	  
                  location2 = {lat:results[0].geometry.location.lat(),lng:results[0].geometry.location.lng()};
                  google.maps.event.addListener(arrivalMarker, 'click', function() {
                	  infowindow.open(map,arrivalMarker);
                	});
				  calculateDistanceAndTime(departureAddress,arrivalAddress,departureTime,polyline,departureMarker,arrivalMarker);
                  
                  } 
                
                else 
                {
                  alert("Geocode was not successful for the following reason: " + status);
                }
              });
    }
    
    function calculateDistanceAndTime(departureAddress,arrivalAddress,departureTime,polyline,departureMarker,arrivalMarker)
	{
    	var currentDate = new Date();
    	var currentTime = currentDate.getTime();
    	
    	distance = distanceCalculator(location1,location2);
    	
    	var travelTimeHour = distance/speed;
    	var travelTimeMillisec = travelTimeHour*60*60*1000;
    	var arrivalTime = departureTime + travelTimeMillisec;

    	var currentTimeDifferenceMillisec = currentTime - departureTime;
    	var currentTimeDifferenceHours = currentTimeDifferenceMillisec/(1000*60*60);
    	var timeRatio = currentTimeDifferenceMillisec/travelTimeMillisec;
    	
    	var numberOfInterval = (distance/speed)*60*60*100;
    	animateFlight(polyline,numberOfInterval,timeRatio,currentTime,departureTime,arrivalTime,departureMarker,arrivalMarker);
    }

    //animate flight
    function animateFlight(polyline,numberOfInterval,timeRatio,currentTime,departureTime,arrivalTime,departureMarker,arrivalMarker){
    	var count = timeRatio*100;
    	//console.log(distance);
    	if (currentTime < departureTime || currentTime > arrivalTime)
    	{
    		polyline.setMap(null);
    		departureMarker.setMap(null);
    		arrivalMarker.setMap(null);
    	}
    	intervalID = window.setInterval(function() {
    		count = count + (100/numberOfInterval);
        	var icons = polyline.get('icons');
        	icons[0].offset = (count) + '%';
        	polyline.set('icons',icons);
    	},10);
    }
    
    rad = function(x) {return x*Math.PI/180;}

    function distanceCalculator(p1, p2) {
      var R = 6371; // earth's mean radius in km
      var dLat  = rad(p2.lat - p1.lat);
      var dLong = rad(p2.lng - p1.lng);

      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c;

      return d.toFixed(3);
    }
    </script>

<title>Flight Map</title>
</head>

<body class="modern-ui" OnLoad="initialize(); ">

<%
	String id = request.getParameter("id");
%>
	<div class="page secondary">
		<div class="page-header">
            <div class="page-header-content">
                <h1>Flight Map</h1>
                <a href="/Website/index_manager.jsp?id=<%=id %>" class="back-button big page-back"></a>
                <div class="user-login">
                    <div class="name">
                        <span class="first-name"><%=id%></span>
                        <span class="last-name"></span>
                    </div>
                    <div class="avatar">
                        <img src="/Website/icon/manager.png"/>
                    </div>
            	</div>
            </div>
        </div>
 	</div>
 	<br>
 	<div>

  	</div>

	<div id="map_canvas" style="position:absolute; top:130px; left:0px; right:0px; bottom:0px"></div>
</body>
</html>